from logger import log
from worker import Worker

START_WORKERS = 2

class Dispatcher:
	def __init__(self):
		self.workers = []
		log('Created Dispatcher')
		for i in range(0, START_WORKERS):
			worker = Worker(self)
			self.workers.append(worker)
			worker.start()

	def getWorkers(self):
		return self.workers

	def printInfo(self):
		log('Workers:')
		for worker in self.getWorkers():
			log('  > Worker (%d/%d)'%(worker.getLoad(),worker.getMaxSlots()))

	def dispatchUnit(self, unit):
		leastLoaded = None
		for worker in self.workers:
			if (not leastLoaded or worker.getLoad() < leastLoaded.getLoad()) and worker.hasSlots():
				leastLoaded = worker

		if not leastLoaded:
			log('No free workers. Spawning new worker')
			worker = Worker(self)
			self.workers.append(worker)
			worker.addUnit(unit)
			worker.start()
		else:
			log('Found least loaded worker: %s'%leastLoaded)
			leastLoaded.addUnit(unit)

		log('Dispatching user')

	def broadcastEvent(self, event, exclude = [], map = None, target = None):
		for worker in self.workers:
			worker.broadcastEvent(event, exclude, map, target)

	def getUnits(self):
		units = []
		for worker in self.workers:
			units.extend(worker.getUnits())
		return units
